package com.cande.loki.exercise.manythread;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * @auther ROCK CODER
 * @DATE 2022/4/4 10:21
 * @Description 实现一个容器，提供两个方法add，size。
 * 写两个线程线程一添加10个元素到容器中，线程2实现监控元素的个数，当个数为5时线程2给出提示并结束
 */
public class TaoBaoInterview {


    volatile List list = new ArrayList();   //只用volatile 是不够的

    public void add(Object o) {
        list.add(o);
    }

    public int size() {
        return list.size();
    }

    public static void main(String[] args) {
        TaoBaoInterview taobao = new TaoBaoInterview();
        final Object o = new Object();
        new Thread(() -> {

            for (int i = 0; i < 10; i++) {
                taobao.add(new Object());
                synchronized (o) {
                    System.out.println("add:" + i);
                    if (i == 4) {
                        o.notify();
                        try {
                            o. wait();
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                }
                try {
                    TimeUnit.SECONDS.sleep(1);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }, "t1").start();

        new Thread(() -> {
            synchronized (o) {
                if (taobao.size() < 5) {
                    try {
                        o.wait();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
                System.out.println("t2 is over");
                o.notify();     //
            }
        }, "t2").start();
    }
}


